package com.hd.quartz.common;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <h3>partitionjob</h3>
 * <p>Query</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2020-09-15 15:56
 **/
@Data
public class Query<T> extends LinkedHashMap<String, Object> {

    private static final long serialVersionUID = -4855691443308100381L;

    private Page<T> page;

    /**
     * 当前页码
     */
    private int currPage = 1;
    /**
     * 每页条数
     */
    private int limit = 10;

    public Query(JQPageInfo pageInfo) {
        //分页参数
        if(pageInfo.getCurPage() != null) {

        }
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String sidx = SQLFilter.sqlInject(pageInfo.getSidx());
        String order = SQLFilter.sqlInject(pageInfo.getOrder());

        //mybatis-plus分页
        this.page = new Page<>(pageInfo.getCurPage(), pageInfo.getLimit());
        //排序 : 升序降序 待 区分
        if(StringUtils.isNotBlank(order)){
            this.page.setAsc(order);
        }

    }


    public Query(Map<String, Object> params){
        this.putAll(params);

        //分页参数
        if(params.get("page") != null){
            currPage = Integer.parseInt((String)params.get("page"));
        }
        if(params.get("limit") != null){
            limit = Integer.parseInt((String)params.get("limit"));
        }

        //偏移量 offset
        this.put("offset", (currPage - 1) * limit);
        this.put("page", currPage);
        this.put("limit", limit);

        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String sidx = SQLFilter.sqlInject((String)params.get("sidx"));
        String order = SQLFilter.sqlInject((String)params.get("order"));
        this.put("sidx", sidx);
        this.put("order", order);

        //mybatis-plus分页
        this.page = new Page<>(currPage, limit);

        //排序
        if(StringUtils.isNotBlank(sidx) && StringUtils.isNotBlank(order)){
//            this.page.setOrderByField(sidx);
//            this.page.setAsc("ASC".equalsIgnoreCase(order));
            this.page.setAsc(order);
        }

    }
}
